// ============ 新增：左侧导航高亮逻辑 ============
function highlightSidebar() {
    // 获取当前页面的路径（比如当前是角色管理页，路径是 role.html）
    const currentPage = window.location.pathname.split('/').pop();
    // 【关键修复】修正页面和导航ID的映射：确保 role.html 对应 roleManagementLink
    const navMap = {
        'user.html': 'userManagementLink',    // 用户管理页 → 用户管理导航
        'department.html': 'departmentManagementLink', // 部门管理页 → 部门管理导航
        'role.html': 'roleManagementLink',    // 角色管理页 → 角色管理导航（这里是核心）
        'profile.html': 'profileLink'         // 个人信息页 → 个人信息导航
    };
    // 先移除所有导航的 active 类
    document.querySelectorAll('#sidebar-nav .nav-link').forEach(link => {
        link.classList.remove('active');
    });
    // 根据当前页面，给对应的导航添加 active 类（高亮）
    const targetLinkId = navMap[currentPage];
    if (targetLinkId) {
        document.getElementById(targetLinkId)?.classList.add('active');
    }
}

// ============ 原有全局变量 ============
const url = "/api/rest/user";
let addForm = document.getElementById('add-form');
let gridInstance = null;
let userData = null;

// 列表表头及操作按钮配置
let columns = [
    { name: '#', id: 'id', width: '8%' },
    { name: '用户名', id: 'username', sort: true },
    { name: '姓名', id: 'name', sort: true },
    { name: '邮箱', id: 'email', sort: true },
    { name: '电话', id: 'phone', sort: true },
    { name: '创建时间', id: 'createAt', sort: true },
    { name: '状态', id: 'enableState', sort: true },
    { name: '部门', id: 'dept.name', sort: true },
    {
        name: '操作',
        id: 'actions',
        width: '20%',
        formatter: (_, row) => gridjs.html(`
            <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit" ></i> 编辑</button>
            <button type="button" onclick="toggle('${row.cells[0].data}')" class="btn btn-sm btn-outline-${row.cells[6].data === '启用' ? 'danger' : 'success'} m-1"><i class="fas fa fa-exchange" ></i> ${row.cells[6].data === '启用' ? '停用' : '启用'}</button>
        `)
    }
]

// ============ 登录状态校验 ============
// if (localStorage.getItem('user') !== 'true') {
//     alert('请先登录系统！');
//     window.location.href = 'login.html';
//     throw new Error('未登录，已跳转');
// }

// 在url末尾添加请求参数
function addQueryParam(url, param) {
    let separator = url.indexOf('?') !== -1 ? '&' : '?';
    return url + separator + param;
}

// 使用gridjs初始化表格
function initGrid() {
    if (gridInstance) {
        gridInstance.destroy(); // 销毁旧实例（用于刷新时重建）
    }

    // 修复：原代码重复创建gridInstance，合并为一次初始化
    gridInstance = new gridjs.Grid(gridOptions).render(document.getElementById("gridjs-container"));
}

// ============ 原有gridOptions配置（无需修改） ============
const gridOptions = {
    columns: [
        { name: '#', id: 'id', width: '8%' },
        { name: '用户名', id: 'username', sort: true },
        { name: '姓名', id: 'name', sort: true },
        { name: '邮箱', id: 'email', sort: true },
        { name: '电话', id: 'phone', sort: true },
        { name: '创建时间', id: 'createAt', sort: true },
        { name: '状态', id: 'enableState', sort: true },
        { name: '部门', id: 'dept.name', sort: true },
        {
            name: '操作',
            id: 'actions',
            width: '20%',
            formatter: (_, row) => gridjs.html(`
                <button type="button" data-bs-toggle="modal" data-bs-target="#editModal" class="btn btn-sm btn-outline-primary m-1"><i class="fas fa-edit" ></i> 编辑</button>
                <button type="button" onclick="toggle('${row.cells[0].data}')" class="btn btn-sm btn-outline-${row.cells[6].data === '启用' ? 'warning' : 'success'} m-1"><i class="fas fa fa-exchange" ></i> ${row.cells[6].data === '启用' ? '停用' : '启用'}</button>
            `)
        }
    ],
    server: {
        url: url,
        then: data => {
            userData = data.content
            return data.content.map(
                user => [
                    user.id,
                    user.username,
                    user.name,
                    user.email,
                    user.phone,
                    user.createAt,
                    user.enableState,
                    user.dept.name
                ]
            )
        },
        total: data => data.totalElements
    },
    pagination: {
        limit: 5, // 每页5条
        server: {
            url: (prev, page, limit) => addQueryParam(prev, `size=${limit}&page=${page}`)
        }
    },
    search: false,
    sort: true,   // 启用排序
    language: {
        pagination: {
            previous: '上一页',
            next: '下一页',
            showing: '显示第',
            of: '条，共',
            to: '至',
            results: '条记录'
        }
    }
}

// ============ 页面加载完成后执行 ============
document.addEventListener('DOMContentLoaded', function() {
    // 1. 先执行导航高亮
    highlightSidebar();
    // 2. 初始化表格
    initGrid();
    // 3. 初始化部门和角色下拉框
    initDept();
    initRole();

    // 填充edit表单
    gridInstance.on('cellClick', (...args) => {
        const event = args[0]
        const userId = args[3].cells[0].data
        let user = userData.find(i => i.id === userId);
        if (event.target) {
            editForm.elements['id'].value = userId
            editForm.querySelector('[name="username"]').value = user.username;
            editForm.querySelector('[name="name"]').value = user.name;
            editForm.querySelector('[name="phone"]').value = user.phone;
            editForm.querySelector('[name="email"]').value = user.email;
            editForm.querySelector('[name="deptId"]').value = user.dept.id;
            editForm.querySelector('[name="roleId"]').value = user.role.id;
        }
    });
});

// ============ 原有函数（initDept/initRole/formJsonData等，无需修改） ============
function initDept() {
    fetch('/api/rest/dept/all')
        .then((response) => response.json())
        .then((data) => {
            let addSelectElement = addForm.querySelector('[name="deptId"]');
            let editSelectElement = editForm.querySelector('[name="deptId"]');
            data.forEach(item => {
                let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;
                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);
                addSelectElement.appendChild(addOption);
                editSelectElement.appendChild(editOption);
            });
        })
        .catch(error => console.error('Error:', error));
}

function initRole() {
    fetch('/api/rest/role/all')
        .then((response) => response.json())
        .then((data) => {
            let addSelectElement = addForm.querySelector('[name="roleId"]');
            let editSelectElement = editForm.querySelector('[name="roleId"]');
            data.forEach(item => {
                let option = document.createElement('option');
                option.value = item.id;
                option.innerText = item.name;
                let addOption = option.cloneNode(true);
                let editOption = option.cloneNode(true);
                addSelectElement.appendChild(addOption);
                editSelectElement.appendChild(editOption);
            });
        })
        .catch(error => console.error('Error:', error));
}

function formJsonData(form) {
    const jsonData = {}
    const formData = new FormData(form);
    formData.forEach((value, key) => {
        if (!jsonData[key]) {
            jsonData[key] = formData.getAll(key).length > 1 ? formData.getAll(key) : formData.get(key);
        }
    });
    return jsonData;
}

// 监听新增按钮
addForm.addEventListener('submit', (event) => {
    event.preventDefault();
    if (addForm.checkValidity()) {
        let jsonData = formJsonData(addForm)
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(jsonData)
        }).then(response => {
            if (response.ok) {
                const userModal = document.getElementById('addModal');
                bootstrap.Modal.getInstance(userModal).hide();
                initGrid();
                Toastify({
                    text: "成功添加新用户",
                    duration: 3000,
                    close: true,
                    backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                    style: { borderRadius: "10px" }
                }).showToast();
            } else {
                response.json().then(data => alert(data.message, 'danger', document.getElementById('alertAddMessage')))
            }
        });
    } else {
        addForm.classList.add('was-validated');
    }
});

// 文件上传
let fileInput = document.getElementById('e_fileInput');
fileInput.addEventListener('change', function () {
    const file = fileInput.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', '头像');
    fetch('/api/rest/attachment', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => editForm.querySelector('[name="avatar"]').value = data.id);
});

let editForm = document.getElementById('edit-form');
// 编辑表单提交
editForm.addEventListener('submit', (event) => {
    event.preventDefault();
    if (editForm.checkValidity()) {
        let jsonData = formJsonData(editForm)
        fetch(`${url}/${jsonData.id}`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(jsonData)
        }).then(response => {
            if (response.ok) {
                const userModal = document.getElementById('editModal');
                bootstrap.Modal.getInstance(userModal).hide();
                initGrid();
                Toastify({
                    text: "编辑用户成功",
                    duration: 3000,
                    close: true,
                    backgroundColor: "linear-gradient(to right, #00b09b, #96c93d)",
                    style: { borderRadius: "10px" }
                }).showToast();
            } else {
                response.json().then(data => alert(data.message, 'danger', document.getElementById('alertEditMessage')))
            }
        });
    } else {
        editForm.classList.add('was-validated');
    }
})



function toggle(id) {
    fetch(url + '/' + id + '/toggle', {method: 'PATCH'})
    .then(response => gridInstance.forceRender())
    .catch(error => console.error('Error:', error));
}

// 定义退出登录函数
function logout() {
    if (confirm('确定要退出登录吗？')) {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        window.location.href = 'login.html';
    }
}